package com.cloud.core.mysql;

import java.io.IOException;
import java.io.Reader;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 1Cloud1
 * @author Administrator
 * @since 2015-11-4
 * @version 1.0 
 */
@Component("Connect")
public class Connect {
	@Value("${mysql.driver}")
	public String driver;
	@Value("${mysql.url}")
	public String url;
	@Value("${mysql.username}")
	public String username;
	@Value("${mysql.password}")
	public String password;
	@Value("${mysql.poolMaximumActiveConnections}")
	public String poolMaximumActiveConnections;
	@Value("${mysql.poolMaximumIdleConnections}")
	public String poolMaximumIdleConnections;
	@Value("${mysql.poolMaximumCheckoutTime}")
	public String poolMaximumCheckoutTime;
	@Value("${mysql.poolTimeToWait}")
	public String poolTimeToWait;
	@Value("${mysql.poolPingConnectionsNotUsedFor}")
	public String poolPingConnectionsNotUsedFor;
	private SqlSessionFactory xonnfileSqlSessionFactory = null;

	@PostConstruct
	private SqlSessionFactory getFileSqlSessionFactory() throws IOException {
		if (xonnfileSqlSessionFactory == null) {
			Reader file = Resources.getResourceAsReader("mybatis/databaseCfg.xml");
			xonnfileSqlSessionFactory = new SqlSessionFactoryBuilder().build(file, "cloud");
			/*Configuration con = xonnfileSqlSessionFactory.getConfiguration();
			Environment environment = con.getEnvironment();
			PooledDataSource dataSource = (PooledDataSource)environment.getDataSource();
			dataSource.setDriver(driver);
			dataSource.setUrl(url);
			dataSource.setUsername(username);
			dataSource.setPassword(password);
			dataSource.setPoolMaximumActiveConnections(Integer.valueOf(poolMaximumActiveConnections));
			dataSource.setPoolMaximumIdleConnections(Integer.valueOf(poolMaximumIdleConnections));
			dataSource.setPoolMaximumCheckoutTime(Integer.valueOf(poolMaximumCheckoutTime));
			dataSource.setPoolTimeToWait(Integer.valueOf(poolTimeToWait));
			dataSource.setPoolPingQuery("select now()");
			dataSource.setPoolPingEnabled(true);
			dataSource.setPoolPingConnectionsNotUsedFor(Integer.valueOf(poolPingConnectionsNotUsedFor));*/
		}
		return xonnfileSqlSessionFactory;
	}
	
	@PreDestroy
	public void destroy(){
		xonnfileSqlSessionFactory = null;
	}

	public SqlSession getSession(boolean autoCommit) {
		SqlSession xonnfileSession = null;
		try {
			xonnfileSession = getFileSqlSessionFactory().openSession(autoCommit);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return xonnfileSession;
	}
}
